<template>
  <div class="seting-box">
    <!--自定义头部-->
    <custom-header :title="'帐号管理'"></custom-header>
    <div class="input-item">
      <!--昵称输入框-->
      <van-field v-model="nickName" label="昵称"/>
      <!--个签输入框-->
      <van-field v-model="introduceSign" label="个性签名"/>
      <!--密码输入框-->
      <van-field v-model="password" type="password" label="修改密码" />
    </div>
    <!--块级按钮，占满一行-->
    <van-button :disabled="!isChange" round class="save-btn" color="#1baeae" type="primary" @click="save" block>保存</van-button>
    <van-button round class="save-btn" color="#1baeae" type="primary" @click="handleLogout" block>退出登录</van-button>
  </div>
</template>
<script>
import { reactive, onMounted, toRefs, watch } from 'vue'
import md5 from 'js-md5'
import CustomHeader from 'components/CustomHeader.vue' //公用头部组件
import { getUserInfo, EditUserInfo, logout } from 'service/user' //用户信息相关接口
import { removeLocal } from 'utils/help' //本地操作工具函数
import { Toast } from 'vant' //单独引入提示组件
export default {
  components: {
    CustomHeader //注册引入的头部组件
  },
  setup() {
    const state = reactive({
      nickName: '', //昵称变量
      introduceSign: '', //个性签名变量
      password: '', //密码变量
      isChange: false
    })
    //初始化方法
    onMounted(async() => {
      //接口获取跟人信息
      const { data } = await getUserInfo()
      //设置个人信息
      state.nickName = data.nickName
      state.introduceSign = data.introduceSign 
      //监听state的变化
      watch(state, () => {
        //当数据变化时，将保存按钮恢复为可单击状态
        state.isChange = true
      })
    })
    //保存方法
    const save = async () => {
      //提交的参数
      const params = { 
        introduceSign: state.introduceSign,
        nickName: state.nickName 
      }
      //当密码有输入时，添加passwordMd5参数到params变量中
      if(state.password){
        //md5加密
        params.passwordMd5 = md5(state.password)
      }
      await EditUserInfo(params)
      Toast.success('保存成功')
    }
    //登出方法
    const handleLogout = async() => {
      //调用登出接口
      const { resultCode } = await logout()
      if(resultCode == 200) {
        //成功后，清除本地token信息
        removeLocal('token')
        //返回首页，使用window.location.href的目的是刷新页面，重新执行src/utils/axios.js中的头部token信息
        window.location.href = '/'
      }
    }
    //返回变量和方法给模板使用
    return {
      ...toRefs(state),
      save,
      handleLogout
    }
  }
}
</script>
<style lang="less" scoped>
  .seting-box {
    .save-btn {
      width: 80%;
      margin: 20px auto;
    }
  }
</style>